<?php
function get_all_compat_version()
{
    return array(
        '200' => 'V2 开发者预览版【2.0.0】',
        '210' => 'V2 RC版【2.1.0】',
        '220' => 'V2 开发版【2.2.0】',
        '230' => 'V2 正式版【2.3.0】'
    );
}

function decode_compat($version)
{
    $version_list = get_all_compat_version();
    $result = array();
    foreach ($version as $v) {
        $result[] = $version_list[$v];
    }
    return $result;
}

function decode_compat_to_array_from_db($version)
{
    $version = str_replace('[', '', $version);
    $version = str_replace(']', '', $version);
    $version = explode(',', $version);
    return $version;
}

function decode_compat_by_str($version)
{
    $version = str_replace('[', '', $version);
    $version = str_replace(']', '', $version);
    $version = explode(',', $version);
    $versions = decode_compat($version);
    $return = '';
    foreach ($versions as $tag) {
        $return .= '<span class="label label-success" style="margin:5px">' . $tag . '</span>';
    }
    return $return;
}

function get_type_select($entity = 1)
{

    $type = D('AppstoreType')->where(array('status' => 1, 'entity' => $entity))->select();
    $options = array();
    $options[''] = '- 选择一个分类 -';
    foreach ($type as $v) {
        $options[$v['id']] = $v['title'];
    }
    return $options;
}

function display_fee_detail($version_id)
{
    $version = D('AppstoreVersion')->getVersion($version_id);
    if ($version['need_buy'] == 0) {
        return '<span class="free">免费 Free</span>';
    } else {
        $price = D('AppstorePrice')->where(array('version_id' => $version_id, 'pid' => 0))->order('id asc')->select();
        $score = D('Ucenter/Score')->getType(array('id' => $price[0]['value']));
        $html = '';
        $new_price = '<div > ';
        $has_cut = false;
        foreach ($price as $key => &$val) {
            $val['score'] = D('Ucenter/Score')->getType(array('id' => $val['value']));
            $new_price .= '<div><td><span class="o_price"> ' . $val['score']['title'] . '&nbsp;<span style="font-size:20px">' . $val['price'] . '</span>&nbsp;' . $val['score']['unit'] . '</span>';
            $val['child'] = D('AppstorePrice')->where(array('version_id' => $version_id, 'pid' => $val['id']))->order('id asc')->select();
            $history = D('AppstorePriceMax')->where(array('score_id' => $val['value'], 'uid' => get_uid(), 'goods_id' => $version['goods_id']))->find();
            if ($val['child'] || $history) {
                $new_price .= '<ul class="rebate_ul">';
                if ($history) {
                    $differ = $val['price'] - $history['max_price'];

                    $differ = 0;   //todo 暂时已购买用户免费升级。 2015/10/20 駿濤
                    if ($differ > 0) {
                        $new_price .= '<li>补差价：<span class="re_price">' . $val['score']['title'] . $differ . $val['score']['unit'] . '</span>升级</li>';

                    } else {
                        $new_price .= '<li style="color: #008000;font-weight: bold"><span class="re_price">免费</span>升级</li>';
                    }
                }
                if ($val['child']) {
                    foreach ($val['child'] as $k => $v) {
                        $role = D('Admin/Role')->getByMap(array('id' => $v['value']));
                        if ($v['price_type'] == 'price') {
                            $p = $val['score']['title'] . $v['price'] . $val['score']['unit'];
                            $new_price .= '<li> ' . $role['title'] . '特价 <span class="re_price"> ' . $p . '</span></li>';
                            $has_cut = true;
                        } else {
                            $p = $val['score']['title'] . $v['price'] . '%';
                            $new_price .= '<li> ' . $role['title'] . '享受 <span class="re_price">' . $p . ' </span> 折扣</li>';
                            $has_cut = true;
                        }
                    }
                }

                $new_price .= '</ul>';
            }
            $new_price .= '</td></div>';
        }
        $new_price .= '</div>';
        $html .= '' . $new_price;
        return $html;
    }
}

function display_fee_tiny($version_id)
{
    $version = D('AppstoreVersion')->getVersion($version_id);
    if ($version['need_buy'] == 0) {
        return '免费';
    } else {
        $price = D('AppstorePrice')->where(array('version_id' => $version_id, 'pid' => 0))->order('id asc')->select();
        $score = D('Ucenter/Score')->getType(array('id' => $price[0]['value']));
        $html = '<a href="' . U('goodsDetail', array('id' => $version['goods_id'])) . '">' . $score['title'] . '&nbsp;' . $price[0]['price'] . '&nbsp;' . $score['unit'];

        $has_cut = false;
        foreach ($price as $key => &$val) {
            $val['score'] = D('Ucenter/Score')->getType(array('id' => $val['value']));

            $val['child'] = D('AppstorePrice')->where(array('version_id' => $version_id, 'pid' => $val['id']))->order('id asc')->select();
            $history = D('AppstorePriceMax')->where(array('score_id' => $val['value'], 'uid' => get_uid(), 'goods_id' => $version['goods_id']))->find();
            if ($val['child']) {
                foreach ($val['child'] as $k => $v) {
                    $role = D('Admin/Role')->getByMap(array('id' => $v['value']));
                    if ($v['price_type'] == 'price') {
                        $has_cut = true;
                    } else {
                        $has_cut = true;
                    }
                }
            }
        }

        $html .= ($has_cut != '' ? '<span style="font-size: 12px;" class="text-danger"> 优惠</span>' : '') . '</a>';
        return $html;
    }
}

function display_fee($version_id)
{
    $version = D('AppstoreVersion')->getVersion($version_id);
    if ($version['need_buy'] == 0) {
        return '免费';
    } else {
        $price = D('AppstorePrice')->where(array('version_id' => $version_id, 'pid' => 0))->order('id asc')->select();
        $score = D('Ucenter/Score')->getType(array('id' => $price[0]['value']));
        $html = '<a  data-toggle="popover" data-placement="right" data-target="$next" data-original-title="" title="" >' . $score['title'] . '&nbsp;' . $price[0]['price'] . '&nbsp;' . $score['unit'];
        $new_price = '<div class="popover no-arrow fade right in"> <div class="arrow"></div><h3 class="popover-title">价格</h3><table class="table"> <tbody>';
        $has_cut = false;
        foreach ($price as $key => &$val) {
            $val['score'] = D('Ucenter/Score')->getType(array('id' => $val['value']));
            $new_price .= '<tr><td><span class="o_price">价格： ' . $val['score']['title'] . '&nbsp;' . $val['price'] . '&nbsp;' . $val['score']['unit'] . '</span>';
            $val['child'] = D('AppstorePrice')->where(array('version_id' => $version_id, 'pid' => $val['id']))->order('id asc')->select();
            $history = D('AppstorePriceMax')->where(array('score_id' => $val['value'], 'uid' => get_uid(), 'goods_id' => $version['goods_id']))->find();
            if ($val['child'] || $history) {
                $new_price .= '<ul class="rebate_ul">';
                if ($history) {
                    $differ = $val['price'] - $history['max_price'];
                    $differ = 0;   //todo 暂时已购买用户免费升级。 2015/10/20 駿濤
                    if ($differ > 0) {
                        $new_price.='<li>已购买用户通过补差价：<span class="re_price">' . $val['score']['title'] . $differ . $val['score']['unit'] . '</span>升级</li>';
                    } else {
                        $new_price .= '<li>已购买用户<span class="re_price">免费</span>升级</li>';
                    }
                }
                if ($val['child']) {
                    foreach ($val['child'] as $k => $v) {
                        $role = D('Admin/Role')->getByMap(array('id' => $v['value']));
                        if ($v['price_type'] == 'price') {
                            $p = $val['score']['title'] . $v['price'] . $val['score']['unit'];
                            $new_price .= '<li>优惠： ' . $role['title'] . '仅需 <span class="re_price"> ' . $p . '</span></li>';
                            $has_cut = true;
                        } else {
                            $p = $val['score']['title'] . $v['price'] . '%';
                            $new_price .= '<li>优惠： ' . $role['title'] . '享受 <span class="re_price">' . $p . ' </span> 折扣</li>';
                            $has_cut = true;
                        }
                    }
                }

                $new_price .= '</ul>';
            }
            $new_price .= '</td></tr>';
        }
        $new_price .= ' </tbody></table></div>';
        $html .= ($has_cut != '' ? '<span style="font-size: 12px;" class="text-danger"> 优惠</span>' : '') . '</a>' . $new_price;
        return $html;
    }
}

function display_cover($cover, $width = 90, $height = 90, $class = '')
{
    if (intval($cover) == 0) {
        $img = C('TMPL_PARSE_STRING.__IMG__');
        echo <<<Eof
 <img class="appstore_cover$class" src="{$img}/no_icon.png"/>
Eof;
    } else {
        $cover = getThumbImageById($cover, $width, $height);
        echo <<<Eof
<img class="appstore_cover$class" src = "{$cover}"/>
Eof;

    }
}

function display_download($id, $class = 'btn')
{
    $id = intval($id);
    if ($id == 0) {
        return '';
    }
    $version = D('AppstoreVersion')->find($id);
    if (intval($version['need_buy']) != 0) {
        $goods=  D('AppstoreVersion')->getVersion($id);
        $check = D('AppstoreGoods')->checkGoodsIsBuy($goods['goods_id'],is_login());

        if (!$check) {
            $order = D('AppstoreOrder')->where(array('version_id' => $id, 'uid' => get_uid(),'status'=>1))->find();
            if ($order) {
                return '<a class="btn-block btn btn-info" href="' . U('Appstore/Index/order', array('id' => $order['id'])) . '"><i class="icon-credit"></i> 付款</a>';
            } else {
                $last = get_last_version($goods['goods_id']);
                if($last['id'] == $id){
                    return '<a class="btn-block btn btn-danger" href="' . U('Appstore/Index/buy', array('id' => $id)) . '"><i class="icon-credit"></i> 购买</a>';
                }else{
                    return '';
                }
            }


        } else {
            if (intval($version['pack']) == 0) {
                return '未上传';
            }
            return '<a class="btn-block btn-success ' . $class . '" href="' . U('index/setup', array('id' => $id)) . '"><i class="icon-cloud-download"></i> 已购买，安装</a>';
        }
    } else {
        if (intval($version['pack']) == 0) {
            return '未上传';
        }
        return '<a class="btn-block ' . $class . '" href="' . U('index/setup', array('id' => $id)) . '"><i class="icon-cube"></i> 免费，安装</a>';
    }

}

function display_download_home($id, $class = 'btn'){
    $id = intval($id);
    if ($id == 0) {
        return '';
    }
    $version = D('AppstoreVersion')->find($id);
    if (intval($version['need_buy']) != 0) {
        $goods=  D('AppstoreVersion')->getVersion($id);
        $check = D('AppstoreGoods')->checkGoodsIsBuy($goods['goods_id'],is_login());

        if (!$check) {
            $order = D('AppstoreOrder')->where(array('version_id' => $id, 'uid' => get_uid(),'status'=>1))->find();
            if ($order) {
                return '<a class="btn-block btn btn-info" href="' . U('Appstore/Index/order', array('id' => $order['id'])) . '"><i class="icon-credit"></i> 付款</a>';
            } else {
                $last = get_last_version($goods['goods_id']);
                if($last['id'] == $id){
                    return '<a class="btn-block btn btn-danger" href="' . U('Appstore/Index/buy', array('id' => $id)) . '"><i class="icon-credit"></i> 购买</a>';
                }else{
                    return '';
                }
            }


        } else {
            if (intval($version['pack']) == 0) {
                return '未上传';
            }
            return '<a class="' . $class . '" href="' . U('index/setup', array('id' => $id)) . '"><i class="icon-cloud-download"></i> 已购买，安装</a>';
        }
    } else {
        if (intval($version['pack']) == 0) {
            return '未上传';
        }
        return '<a class=" ' . $class . '" href="' . U('index/setup', array('id' => $id)) . '"><i class="icon-cube"></i> 免费，安装</a>';
    }

}
function display_buy($id, $class = 'btn')
{
    $id = intval($id);
    if ($id == 0) {
        return '';
    }
    $version = D('AppstoreVersion')->find($id);
    if (intval($version['need_buy']) != 0) {
        $order = D('AppstoreOrder')->where(array('version_id' => $id, 'uid' => get_uid(), 'status' => 1, 'pay_ok' => 0))->find();
        if ($order) {
            return '<a class="btn-block btn btn-info" href="' . U('Appstore/Index/order', array('id' => $order['id'])) . '"><i class="icon-credit"></i> 付款</a>';
        } else {
            return '<a class="btn-block btn btn-danger" href="' . U('Appstore/Index/buy', array('id' => $id)) . '"><i class="icon-credit"></i> 下单</a>';
        }
    } else {

        return '<a class="btn-block ' . $class . '" href="' . U('index/setup', array('id' => $id)) . '"><i class="icon-cube"></i> 免费，下单</a>';
    }
}

function display_download_times($times)
{
    if (0 && $times < 50) {
        return '少于50';
    } elseif ($times > 999) {
        return '999+';
    } else {
        return $times;
    }
}

function display_version($version_name, $label = false)
{
    if (text($version_name) == '') {
        $return = $label == true ? '<span class="label">暂无新版</span>' : '暂无新版';
    } else {
        $return = $label == true ? '<span class="label label-success">' . text($version_name) . '</span>' : text($version_name);
    }
    return $return;
}

function display_shop($goods_id)
{
    $goods = D('AppstoreGoods')->find($goods_id);
    $shop = D('AppstoreShop')->find($goods['uid']);
    if ($shop && $shop['status'] == 1) {
        if ($shop['gold'] || $shop['official'])
            $css = 'color:red'; else {
            $css = '';
        }

        return '<a style="' . $css . '" href="' . U('Appstore/Index/Shop', array('id' => $shop['uid'])) . '">' . $shop['title'] . '</a>' . display_icon($shop);
    } else {
        $user = query_user(array('space_link'), $goods['uid']);
        return '@'.$user['space_link'];
    }

}

function display_star($shop)
{
    $html='';
    for ($i = 0; $i < $shop['star']; $i++) {
        $html .= ' <img src="' . C('TMPL_PARSE_STRING.__IMG__') . '/star-on.png"/>';
    }
    return $html;

}

function display_icon($shop)
{
    $html = $shop['official'] ? '<img title="官方认证店" alt="官方认证店" src="' . C('TMPL_PARSE_STRING.__IMG__') . '/icon-official.png"/>' : '';
    $html .= $shop['gold'] ? '<img title="金牌店铺" alt="金牌店铺" src="' . C('TMPL_PARSE_STRING.__IMG__') . '/icon-gold.png"/>' : '';
    return $html;

}

function is_tip($uid)
{
    $setting = D('AppstoreDeveloper')->find($uid);
    if (empty($setting)) {
        return true;
    } else {
        return !$setting['refuse_message'];
    }
}

function get_domain($url)
{
    $pattern = "/[/w-]+/.(com|net|org|gov|biz|com.tw|com.hk|com.ru|net.tw|net.hk|net.ru|info|cn|com.cn|net.cn|org.cn|gov.cn|mobi|name|sh|ac|la|travel|tm|us|cc|tv|jobs|asia|hn|lc|hk|bz|com.hk|ws|tel|io|tw|ac.cn|bj.cn|sh.cn|tj.cn|cq.cn|he.cn|sx.cn|nm.cn|ln.cn|jl.cn|hl.cn|js.cn|zj.cn|ah.cn|fj.cn|jx.cn|sd.cn|ha.cn|hb.cn|hn.cn|gd.cn|gx.cn|hi.cn|sc.cn|gz.cn|yn.cn|xz.cn|sn.cn|gs.cn|qh.cn|nx.cn|xj.cn|tw.cn|hk.cn|mo.cn|org.hk|is|edu|mil|au|jp|int|kr|de|vc|ag|in|me|edu.cn|co.kr|gd|vg|co.uk|be|sg|it|ro|com.mo)(/.(cn|hk))*/";
    preg_match($pattern, $url, $matches);
    if (count($matches) > 0) {
        return $matches[0];
    } else {
        $rs = parse_url($url);
        $main_url = $rs["host"];
        if (!strcmp(long2ip(sprintf("%u", ip2long($main_url))), $main_url)) {
            return $main_url;
        } else {
            $arr = explode(".", $main_url);
            $count = count($arr);
            $endArr = array("com", "net", "org"); //com.cn net.cn 等情况
            if (in_array($arr[$count - 2], $endArr)) {
                $domain = $arr[$count - 3] . "." . $arr[$count - 2] . "." . $arr[$count - 1];
            } else {
                $domain = $arr[$count - 2] . "." . $arr[$count - 1];
            }
            return $domain;
        }
    }
}


function get_goods_by_versionid($version_id)
{
    $version = D('AppstoreVersion')->getVersion($version_id);
    $goods = D('AppstoreGoods')->getById($version['goods_id']);
    return $goods;

}


function get_finally_price($price_id)
{
    $price = D('AppstorePrice')->getById($price_id);

    if ($price['pid']) {
        $pPrice = D('AppstorePrice')->getById($price['pid']);
        $score = D('Ucenter/Score')->getType(array('id' => $pPrice['value']));
        if ($price['price_type'] == 'price') {
            $return['payment_price'] = $price['price'];
        } else {
            $return['payment_price'] = $price['price'] * $pPrice['price'] / 100;
        }
        $return['version_price'] = $pPrice['price'];
    } else {
        $score = D('Ucenter/Score')->getType(array('id' => $price['value']));
        $return['payment_price'] = $price['price'];
        $return['version_price'] = $price['price'];
    }
    $return['score'] = $score['id'];
    return $return;
}


function get_pay_condition($order_id)
{
    $order = D('AppstoreOrder')->getById($order_id);
    if ($order) {
        if ($order['status']) {
            if ($order['pay_ok']) {
                return '支付成功';
            } else {
                return '等待付款';
            }
        } else {
            return '该订单已经被取消';
        }

    } else {
        return '还未购买';
    }
}


function get_last_version($goods_id){
    return D('appstore_version')->where(array('goods_id'=>$goods_id,'status'=>1))->order('id desc')->find();
}